/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ipccenter.ejb;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.Remote;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Nick
 */
@Stateless(name = "UserSession", mappedName = "UserSession")
@Remote(UserInterface.class)
public class UserSessionBean implements Serializable, UserInterface {
    @PersistenceContext(unitName="Task-ejbPU")
    EntityManager em;

    protected User user;
    protected Collection<User> userList;

    @Override
    public void addUser(String name, String pass, String mail) {
            user = new User(name, pass, mail);
            em.persist(user);
            em.flush();
            em.clear();
    }
    @Override
    public Collection<User> getAllUsers() {
        userList = em.createNamedQuery("Users.findAllName").getResultList();
        for(Object temp : userList) {
            System.out.println(temp.toString());
        }
        return userList;
    }

    @Override
    public boolean checkPass(String name, String pass) {
        List<String> res = em.createNamedQuery("Users.findPassByUsername").setParameter("username", name).getResultList();
        if(res.contains(pass)) {
            return true;
        }
        return false;
    }
    @Override
    public boolean checkForExistName(String name) {
        List<String> res = em.createNamedQuery("Users.findAllName").getResultList();
        if(res.contains(name)) {
            return true;
        }    
        return false;
    }
    @Override
    public boolean checkForExistMail(String mail) {
        List<String> res = em.createNamedQuery("Users.findAllMail").getResultList();
        if(res.contains(mail)) {
            return true;
        }    
        return false;
    }
    @Override
    public Object[] getPass(String mail) {
        List<Object[]> res = em.createNamedQuery("Users.findPassByMail").setParameter("usermail", mail).getResultList();
        for(Object[] temp : res) {
            return temp;
            //System.out.println(temp[0].toString());
        }
        return null;
    }
}
